//
//  WebView.swift
//  Swift-WB
//
//  Created by lxy on 2017/6/8.
//  Copyright © 2017年 lixiya. All rights reserved.
//

import UIKit
import WebKit


let KeyLoading = "loading"
let KeyTitle = "title"
let KeyEstimatedProgress = "estimatedProgress"

protocol WebViewDelegate: class {
    
    func wb_estimatedProgress(_ progress: Float) -> ()
    func wb_title(_ title: String?) -> ()
    func wb_receiveScriptMessage(_ message: WKScriptMessage) -> ()
}

class WebView: WKWebView {
    
    weak var wb_delegate: WebViewDelegate?
    
    
    init(frame: CGRect, scriptMessageHandlerNames: [String]) {

        // 创建配置项
        let configuration = WKWebViewConfiguration()
        super.init(frame: frame, configuration: configuration)
        
        // 偏好设置
        configuration.preferences = WKPreferences()
        configuration.preferences.minimumFontSize = 13
        configuration.preferences.javaScriptEnabled = true
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
        
        // js与webview内容交互配置
        configuration.userContentController = WKUserContentController()
        for name in scriptMessageHandlerNames {
            configuration.userContentController.add(self, name: name)
        }
        
        // 监听KVO
        self.addObserver(self, forKeyPath: KeyLoading, options: .new, context: nil)
        self.addObserver(self, forKeyPath: KeyTitle, options: .new, context: nil)
        self.addObserver(self, forKeyPath: KeyEstimatedProgress, options: .new, context: nil)

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    deinit {
        self.removeObserver(self, forKeyPath: KeyLoading)
        self.removeObserver(self, forKeyPath: KeyTitle)
        self.removeObserver(self, forKeyPath: KeyEstimatedProgress)
    }
    
    
    // MARK: - 监听KVO
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "loading" {
            
        }else if keyPath == "title" {
            wb_delegate?.wb_title(self.title)
        }else if keyPath == "estimatedProgress" {
            let progress = change?[.newKey] as? Float ?? 0
            wb_delegate?.wb_estimatedProgress(progress)
        }
    }
}

extension WebView: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        wb_delegate?.wb_receiveScriptMessage(message)
    }
    
}
